<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="dataForm.username" placeholder="登录帐号"></el-input>
      </el-form-item>
      <blockquote v-if="!dataForm.userId" >
      <el-form-item v-if="dataForm.id === undefined" label="密码" prop="password" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.confirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
      </blockquote>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="dataForm.nickname" placeholder="昵称"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload ref="pictureUpload"
                   class="avatar-uploader"
                   :action="uploadPath"
                   list-type="picture-card" :headers="uploadHeader"
                   :show-file-list="true"
                   :before-upload="beforeUpload"
                   :on-success="uploadSuccess" :limit="1" :file-list="fileList" :on-exceed="onExceed">
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" height="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
const initUser = {
  userId: '',
  username: '',
  password: '',
  confirmPassword: '',
  salt: '',
  nickname: '',
  avatar: '',
  roleIdList: [],
  status: 1
}
export default {
  data () {
    const validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    const validateConfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('确认密码不能为空'))
      } else if (this.dataForm.password !== value) {
        callback(new Error('确认密码与密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      roleList: [],
      dataForm: { ...initUser },
      dataRule: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        password: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ]
      },
      dialogImageUrl: '',
      dialogVisible: false,
      uploadHeader: {
        token: ''
      },
      uploadPath: process.env.VUE_APP_BASE_API + '/upload',
      baseImagePath: process.env.VUE_APP_BASE_API + '/img/',
      fileList: []
    }
  },
  methods: {
    init (userId) {
      this.visible = true
      this.dataForm = { ...initUser, userId }
      this.dialogImageUrl = ''
      if (this.dataForm.userId) {
        this.$http.get(`/sys/user/info/${this.dataForm.userId}`).then(({ data }) => {
          if (data && data.code === 200) {
            this.dataForm = { ...data.user }
            this.fileList.length = 0
            this.fileList.push({ url: this.baseImagePath + this.dataForm.avatar })
          }
        })
      }
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$http.post(`/sys/user/${this.dataForm.userId === undefined ? 'save' : 'update'}`, this.dataForm).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    handleRemove (file) {
      this.$confirm('您确定要移除吗?', '询问').then(() => {
        this.$refs.pictureUpload.handleRemove(file)
      })
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload (file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isImage) {
        this.$message.error('文件格式不正确')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2M')
      }
      return isImage && isLt2M
    },
    uploadSuccess (data) {
      if (data.code === 200) {
        this.dataForm.avatar = data.data
        this.fileList.length = 0
        this.fileList.push({ url: this.baseImagePath + data.data })
      } else {
        this.$message.error(data.msg)
      }
    },
    onExceed () {
      this.$message.error('请先删除原本的图片！')
    }
  },
  created () {
    this.uploadHeader.token = this.$cookies.get('token')
  }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
